#include "net_buffer.h"
#include <netinet/in.h>

using namespace NetKit;

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////


NetBuffer::NetBuffer(uint32_t bytes)
{
	Init(bytes);
}

NetBuffer::~NetBuffer()
{
	Destory();
}

int32_t NetBuffer::GetI32ByLocalBin(uint32_t pos)
{
	int32_t i32 = *(int32_t*)(m_pData+pos);
	//i32 = (int32_t)ntohl(i32);
	return i32;
}

int32_t NetBuffer::GetI32ByHostBin(uint32_t pos)
{
	int32_t i32 = *(int32_t*)(m_pData+pos);
	i32 = (int32_t)ntohl(i32);
	return i32;
}

int32_t NetBuffer::GetIntByText(uint32_t pos, uint32_t bytes)
{
    char szTmp[bytes+1];
    memcpy(szTmp, m_pData+pos, bytes);
    szTmp[bytes] = 0;
    return atoi(szTmp);
}

std::string NetBuffer::GetString(uint32_t pos, uint32_t bytes)
{
	uint32_t outSize = bytes > m_iUsed ? m_iUsed : bytes;
      char szTmp[outSize+1];    
	memcpy(szTmp, m_pData, outSize);
	szTmp[outSize] = '\0';
	return std::string(szTmp);
}

void  NetBuffer::SetData(const char* pSrc, uint32_t bytes)
{
    if ( bytes > m_iSize )
		Grow(bytes-m_iSize);
	Reset();
	memcpy(m_pData, pSrc, bytes);
	m_iUsed = bytes;
}

void NetBuffer::AppendData(const char* pSrc, uint32_t bytes)
{
	if ( bytes > m_iSize-m_iUsed )
		Grow(bytes-(m_iSize-m_iUsed));
	memcpy(m_pData+m_iUsed, pSrc, bytes);
	m_iUsed += bytes;
}

void NetBuffer::Reset()
{
	memset(m_pData, 0, m_iSize);
	m_iUsed = 0;
}

void NetBuffer::Grow(uint32_t bytes)
{
	char* pNewData = new char[m_iSize+bytes];
	memcpy(pNewData, m_pData, m_iUsed);
	m_iSize = m_iSize+bytes;
	delete[] m_pData;
	m_pData = pNewData;
}

void NetBuffer::Init(uint32_t bytes)
{
	m_iSize = bytes;
	m_iUsed = 0;
	m_pData = new char[bytes];
}

void NetBuffer::Destory()
{
	if ( m_pData != NULL )
	{
		delete[] m_pData;
		m_pData = NULL;
	}
}

